package com.bzkj.basicinfo.service.basic.impl;

import com.bzkj.basicinfo.domain.basic.BasicStoArea;
import com.bzkj.basicinfo.domain.basic.BasicStoStock;
import com.bzkj.basicinfo.mapper.BasicStoAreaMapper;
import com.bzkj.basicinfo.mapper.BasicStoStockMapper;
import com.bzkj.basicinfo.service.basic.BasicStoAreaService;
import com.bzkj.basicinfo.service.basic.BasicStoStockService;
import com.bzkj.common.annotation.DataSource;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.domain.model.LoginUser;
import com.bzkj.common.core.page.TableDataInfo;
import com.bzkj.common.enums.DataSourceType;
import com.bzkj.common.utils.DataProcessCommonUtils;
import com.bzkj.common.utils.DateUtils;
import com.bzkj.common.utils.SecurityUtils;
import com.bzkj.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author wl
 * @description 针对表【basic_sto_area(WMS库区信息表)】的数据库操作Service实现
 * @createDate 2024-12-13 11:44:19
 */
@Slf4j
@Service
public class BasicStoAreaServiceImpl implements BasicStoAreaService {

    @Autowired
    private BasicStoAreaMapper basicStoAreaMapper;

    @Autowired
    private BasicStoStockMapper basicStoStockMapper;

    @Override
    public List<BasicStoArea> findStoArea(BasicStoArea entity) {
        return basicStoAreaMapper.findStoArea(entity);
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public AjaxResult selectErpStock(BasicStoArea entity) {
        return AjaxResult.success(basicStoAreaMapper.findErpStock(entity));
    }

    @Override
    public TableDataInfo selectErpMapStockList(BasicStoArea entity, int pageNum, int pageSize) {
        List<BasicStoArea> stoAreaList = basicStoAreaMapper.selectErpMapStockList(entity);
        if (stoAreaList.isEmpty()) {
            return DataProcessCommonUtils.getTableInfo(Collections.emptyList(), pageNum, pageSize);
        }
        return DataProcessCommonUtils.getTableInfo(stoAreaList, pageNum, pageSize);
    }

    @Override
    public AjaxResult insertErpMap(BasicStoArea entity) {
        //校验
        if (Objects.isNull(entity)) {
            return AjaxResult.error("新增失败");
        }
        if (StringUtils.isBlank(entity.getStoId())) {
            return AjaxResult.error("仓库数据不能为空");
        }
        if (StringUtils.isBlank(entity.getStoAreaId())) {
            return AjaxResult.error("库区数据不能为空");
        }
        if (StringUtils.isBlank(entity.getAgentId())) {
            return AjaxResult.error("剂型数据不能为空");
        }
        if (StringUtils.isBlank(entity.getErpCode())) {
            return AjaxResult.error("erp数据不能为空");
        }
        BasicStoArea stoArea = basicStoAreaMapper.selectWmsErpMap(entity.getStoId(), entity.getAgentId(), entity.getErpCode(),
                entity.getErpName(), entity.getStoAreaId());
        if(Objects.nonNull(stoArea)) {
            return AjaxResult.error("当前映射关系已存在，请重新选择");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        int maxNum = basicStoAreaMapper.selectMaxWmsErpId();
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", ++maxNum);
        map.put("sto_id", entity.getStoId());
        map.put("qualified_id", entity.getStoAreaId());
        map.put("area_id", entity.getAgentId());
        map.put("erp_code", entity.getErpCode());
        map.put("erp_huowei_name", entity.getErpName());
        map.put("creator", loginUser.getUser().getNickName());
        map.put("createTime", DateUtils.getNowDate());
        int i = basicStoAreaMapper.insertWmsErpMap(map);
        if (i > 0) {
            return AjaxResult.success("新增成功");
        }
        return AjaxResult.error("新增失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertJiXingMap(BasicStoArea entity) {
        String erpAgentId = entity.getErpAgentId();
        //剂型为空时删除掉原有的映射
        if (StringUtils.isBlank(erpAgentId)) {
            int i = basicStoAreaMapper.deleteJiXingMap(entity.getAreaId());
            if (i > 0) {
                return AjaxResult.success("修改成功");
            }
        }
        // 获取当前登录用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        try {
            // 分割机型字符串为列表
            List<String> jixingList = Arrays.asList(erpAgentId.split(","));
            if (jixingList.isEmpty()) {
                return AjaxResult.error("未获取到有效剂型信息");
            }
            String creator = loginUser.getUser().getNickName();
            Date createTime = DateUtils.getNowDate();
            int totalInserted = 0;
            int maxNum = basicStoAreaMapper.selectMaxJiXingId();
            // 批量插入处理
            for (String jixing : jixingList) {
                if (StringUtils.isNotBlank(jixing)) {
                    Map<String, Object> paramMap = new HashMap<>(4);
                    paramMap.put("id", ++maxNum);
                    paramMap.put("area_id", entity.getAreaId());
                    paramMap.put("jixing", jixing.trim());  // 去除前后空格
                    paramMap.put("creator", creator);
                    paramMap.put("createTime", createTime);
                    totalInserted += basicStoAreaMapper.insertJiXingMap(paramMap);
                }
            }
            if (totalInserted > 0) {
                return AjaxResult.success("新增成功，共插入" + totalInserted + "条记录");
            } else {
                return AjaxResult.error("新增失败");
            }
        } catch (Exception e) {
            log.error("插入机型映射关系失败", e);
            return AjaxResult.error("操作失败：" + e.getMessage());
        }
    }

    @Override
    public AjaxResult deleteErpMap(BasicStoArea entity) {
        List<BasicStoArea> stoAreas = basicStoAreaMapper.selectJiXingMap(entity.getAreaId());
        if (!stoAreas.isEmpty()) {
            return AjaxResult.error("存在关联erp剂型，请先删除关联剂型");
        }
        int i = basicStoAreaMapper.deleteWmsErpMap(String.valueOf(entity.getId()));
        if (i > 0) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    @Override
    public List<BasicStoArea> findStoAreaList(BasicStoArea entity) {
        return basicStoAreaMapper.findStoAreaList(entity);
    }

    @Override
    public List<BasicStoArea> findAllStoAreaList(BasicStoArea entity) {
        return basicStoAreaMapper.findStoAreaList(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addStoArea(BasicStoArea stoArea) {
        //获取当前登录人
        LoginUser loginUser = SecurityUtils.getLoginUser();
        stoArea.setCreateBy(loginUser.getUser().getNickName());
        //查询仓库名称
        BasicStoStock stoStock = basicStoStockMapper.selectStoStockByStoId(stoArea.getStoId());
        if(Objects.nonNull(stoStock)){
            stoArea.setStoName(stoStock.getStoName());
        }
        int i = basicStoAreaMapper.insertWarehouse(stoArea);
        if (i > 0) {
            return AjaxResult.success("新增成功");
        }
        return AjaxResult.error("新增失败");
    }

    /**
     * 库区hw自增处理
     *
     * @param input
     * @return
     */
    public static String increment(String input) {
        // 判空处理
        if (input == null || input.isEmpty()) {
            throw new IllegalArgumentException("输入字符串不能为空");
        }
        // 正则表达式：匹配非数字前缀和数字部分
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("([^\\d]*)(\\d+)");
        java.util.regex.Matcher matcher = pattern.matcher(input);

        if (matcher.find()) {
            String prefix = matcher.group(1); // 前缀部分
            String numberStr = matcher.group(2); // 数字部分

            // 处理数字部分可能的前导零
            int length = numberStr.length();

            try {
                // 将数字部分转为整数并加1
                // 使用BigInteger处理大数（超过Integer.MAX_VALUE的情况）
                java.math.BigInteger number = new java.math.BigInteger(numberStr);
                number = number.add(java.math.BigInteger.ONE);

                // 重新格式化为原长度的字符串（补零）
                String newNumberStr = String.format("%0" + length + "d", number);

                // 拼接前缀和新的数字部分
                return prefix + newNumberStr;
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("输入的数字部分格式错误: " + numberStr, e);
            }
        }

        // 不匹配时直接返回原字符串（可根据需求改为抛出异常）
        log.warn("警告: 输入字符串格式不符合预期，未找到数字部分 - " + input);
        return input;
    }


    @Transactional
    @Override
    public AjaxResult updateStoArea(BasicStoArea stoArea) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        stoArea.setUpdateBy(loginUser.getUser().getNickName());
        stoArea.setUpdateTime(new Date());
        int i = basicStoAreaMapper.updateWarehouse(stoArea);
        if (i > 0) {
            return AjaxResult.success("修改成功");
        }
        return AjaxResult.error("修改成功");
    }

    @Override
    public AjaxResult deleteStoAreaById(String hw) {
        //删除时判断当前库区的货位是否有被占用的

        int i = basicStoAreaMapper.deleteWarehouse(hw);
        if (i > 0) {
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    @Override
    public AjaxResult updateBasicStoAreaEnableStatus(String ckzht, String hw) {
        try {
            basicStoAreaMapper.updateBeactiveStatus(ckzht, hw);
            return AjaxResult.success("修改成功");
        } catch (Exception e) {
            log.error("修改失败:{}", e);
            return AjaxResult.warn("修改失败");
        }
    }

    @Override
    public AjaxResult updateBasicStoAreaStatus(String status, String stoAreaId) {
            int i = basicStoAreaMapper.updateStatus(status, stoAreaId);
            if(i>0){
                return AjaxResult.success("修改成功");
            }else{
                return AjaxResult.error("修改失败");
            }
    }
}




